const axios = require('axios');
const pool = require("../db/connectionPool"); // 导入连接池
const { DATABASE_NAME, DATABASE_USERNAME, HISTORY_PAGE_SIZE, TABLE_CREATE_SUCCESS, DATABASE_HOST, TABLE_HISTORY_NAME, APP_KEY } = require('../constants/constants')
const { saveData, getData } = require('../utils/cache')

function getCaipiaoTypes() {
  const options = {
    method: 'GET',
    url: 'http://apis.juhe.cn/lottery/types',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    params: {
      key: APP_KEY
    }
  };

  return axios(options)
}
function getHisToryResult(lottery_id, pageNum) {
  console.log(`zdy---getHisToryResult--->${lottery_id}`);
  const options = {
    method: 'GET',
    url: 'http://apis.juhe.cn/lottery/history',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer your_token_here'
    },
    params: {
      key: APP_KEY,
      lottery_id: lottery_id,
      page_size: HISTORY_PAGE_SIZE,
      page: pageNum
    }
  };

  return axios(options)

}
function getCacheResult() {
  return new Promise((resolve, reject) => {
    if (!pool) {
      resolve([])
      return
    }
    // 从连接池中获取数据库的连接对象
    pool.getConnection(function (err, conn) {
      if (err) {
        console.log("数据库连接失败");
        resolve([])
      } else {
        console.log("数据库连接成功");
        // 定义sql查询语句
        let sql = "select * from " + TABLE_HISTORY_NAME;
        // 查询操作
        conn.query(sql, function (err, result) {
          if (err) {
            console.log("数据库查询失败");
            resolve([])
          } else {
            console.log("数据库查询成功，数据长度是---》" + result?.length);
            if (result && result.length > 0) {
              resolve(result)
            } else {
              resolve([])
            }
          }
        })
      }

    })
  })
}
async function cacheToDB(item) {
  if (!pool) {
    console.log("pool 是空");
    return
  }
  if (!item) {
    console.log("item 是空");
    return
  }
  return await new Promise((resolve, reject) => {
    pool.getConnection(async function (err, conn) {
      if (err) {
        // console.log("数据库连接失败");
      } else {
        try {
          // console.log("数据库连接成功");
          let lottery_id = item['lottery_id']
          let lottery_res = item['lottery_res']
          let lottery_no = item['lottery_no']
          let lottery_date = item['lottery_date']
          let lottery_exdate = item['lottery_exdate']
          let lottery_sale_amount = item['lottery_sale_amount']
          let lottery_pool_amount = item['lottery_pool_amount']
          // 插入
          // console.log("开始插入");

          // SQL 格式     
          const InsertSQl = `insert into  ${TABLE_HISTORY_NAME}(lottery_id,lottery_res,lottery_no,lottery_date,lottery_exdate,lottery_sale_amount,lottery_pool_amount) values(?,?,?,?,?,?,?)`;
          // 参数格式
          const params = [lottery_id, lottery_res, lottery_no, lottery_date, lottery_exdate, lottery_sale_amount, lottery_pool_amount];

          await conn.query(InsertSQl, params);
          // console.log("插入成功");
          conn.release()
          return resolve('success')
        } catch (err) {
          console.log("插入失败  " + err.message);
          return reject(err)
        }
      }

    })
  })
}
async function getResults(lottery_id, pageNum) {
  try {
    let histtoryResult = await getHisToryResult(lottery_id, pageNum)
    // console.log('历史开奖数据:', JSON.stringify(histtoryResult.data));

    if (!histtoryResult || !histtoryResult.data) {
      return { page: 0, pageSize: HISTORY_PAGE_SIZE, totalPage: 0 }
    }
    let result = histtoryResult.data['result']
    if (!result) {
      return { page: 0, pageSize: HISTORY_PAGE_SIZE, totalPage: 0 }
    }
    let list = result['lotteryResList']
    if (!list || list.length < 1) {
      return { page: 0, pageSize: HISTORY_PAGE_SIZE, totalPage: 0 }
    }
    for (let i = 0; i < list.length; i++) {
      let item = list[i]
      await cacheToDB(item)
    }
    let page = result['page']
    let pageSize = result['pageSize']
    let totalPage = result['totalPage']
    console.log(`存入数据${list.length}条,page-->${page},pageSize-->${pageSize},totalPage-->${totalPage}`);

    if (page == totalPage && list.length <= pageSize) {
      console.log("数据存储完毕");
      saveData('isInitFinish', true)
      saveData('initCount', page)
      return Promise.resolve('success')
    } else {
      saveData('isInitFinish', false)
      saveData('initCount', page)
      return getResults(lottery_id, (pageNum + 1))
    }
  } catch (err) {
    return Promise.reject(err)
  }



}
async function updateResults() {

  try {
    let isInitFinish = getData('isInitFinish')
    let initCount = getData('initCount')
    let pageNum = 1
    // 说明初始化第一次获取所有的数据尚未结束
    if (isInitFinish != true) {
      // 说明没有请求到最后一页 需要继续请求
      if (initCount >= 1) {
        pageNum = initCount;
      }
    } else {
      // 首次初始化完成 说明不需要大量请求数据了 每次只请求一次数据即可 
      // TODO 需要开启定时任务每天检测一次 是否是周一 三 六 以及时间是否是晚上的10:00以后
    }

    let types = await getCaipiaoTypes()
    console.log('彩票类型数据:', types.data);
    if (!types || !types.data) {
      console.log('请求彩票类型数据失败');
      return
    }
    let lottery_id = ''
    if (types.data && types.data['result'] && types.data['result'] instanceof Array) {
      let data = types.data['result']

      for (let i = 0; i < data.length; i++) {
        let item = data[i]
        let lottery_name = item['lottery_name']
        if (lottery_name && typeof lottery_name == 'string' && lottery_name.indexOf('大乐透') != -1) {
          lottery_id = item['lottery_id']
        }
      }
    }
    if (!lottery_id || typeof lottery_id != 'string' || lottery_id.length < 1) {
      console.log('暂未获取到大乐透的id，不更新');
      return
    }
    return getResults(lottery_id, pageNum)
  } catch (err) {
    console.log(`zdy---err--->${err.message}`);
    return Promise.reject(err)
  }


}

module.exports = updateResults